<template>
  <PageContainer title="应用管理" description="管理平台上的所有应用">
    <div class="admin-page-content">
      <!-- 搜索表单 -->
      <GlassCard class="search-card">
      <template #header>
        <h3 class="search-title">筛选条件</h3>
      </template>

      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="应用名称">
          <a-input
            v-model:value="searchParams.appName"
            placeholder="输入应用名称"
            class="glass-input search-input"
          />
        </a-form-item>
        <a-form-item label="创建者">
          <a-input
            v-model:value="searchParams.userId"
            placeholder="输入用户ID"
            class="glass-input search-input"
          />
        </a-form-item>
        <a-form-item label="生成类型">
          <a-select
            v-model:value="searchParams.codeGenType"
            placeholder="选择生成类型"
            class="glass-select search-select"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option
              v-for="option in CODE_GEN_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <GlassButton type="primary" size="small" @click="doSearch" :loading="loading">
            搜索
          </GlassButton>
        </a-form-item>
        <a-form-item>
          <GlassButton type="ghost" size="small" @click="doReset">
            重置
          </GlassButton>
        </a-form-item>
      </a-form>
    </GlassCard>

    <!-- 表格 -->
    <GlassTable
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="doTableChange"
      :scroll="{ x: 1340 }"
      class="app-table"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'cover'">
          <div class="cover-cell">
            <a-image
              v-if="record.cover"
              :src="record.cover"
              :width="80"
              :height="60"
              class="cover-image"
            />
            <div v-else class="no-cover">
              <span>🖼️</span>
              <span>无封面</span>
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'initPrompt'">
          <a-tooltip :title="record.initPrompt">
            <div class="prompt-text">{{ record.initPrompt }}</div>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'codeGenType'">
          <a-tag class="type-tag">{{ formatCodeGenType(record.codeGenType) }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'priority'">
          <a-tag v-if="record.priority === 99" color="gold" class="featured-tag">
            ⭐ 精选
          </a-tag>
          <span v-else class="priority-text">{{ record.priority || 0 }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'deployedTime'">
          <span v-if="record.deployedTime" class="time-text">
            {{ formatTime(record.deployedTime) }}
          </span>
          <span v-else class="not-deployed">未部署</span>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          <span class="time-text">{{ formatTime(record.createTime) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'user'">
          <UserInfo :user="record.user" size="small" />
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <GlassButton type="primary" size="small" @click="editApp(record)">
              编辑
            </GlassButton>
            <GlassButton
              :type="record.priority === 99 ? 'warning' : 'secondary'"
              size="small"
              @click="toggleFeatured(record)"
            >
              {{ record.priority === 99 ? '取消精选' : '精选' }}
            </GlassButton>
            <a-popconfirm title="确定要删除这个应用吗？" @confirm="deleteApp(record.id)">
              <GlassButton type="danger" size="small">删除</GlassButton>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </GlassTable>
    </div>
  </PageContainer>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listAppVoByPageByAdmin, deleteAppByAdmin, updateAppByAdmin } from '@/api/appController'
import { CODE_GEN_TYPE_OPTIONS, formatCodeGenType } from '@/utils/codeGenTypes'
import { formatTime } from '@/utils/time'
import UserInfo from '@/components/UserInfo.vue'
import PageContainer from '@/components/base/PageContainer.vue'
import GlassCard from '@/components/base/GlassCard.vue'
import GlassButton from '@/components/base/GlassButton.vue'
import GlassTable from '@/components/base/GlassTable.vue'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
    fixed: 'left',
    align: 'center',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    width: 150,
    ellipsis: true,
  },
  {
    title: '封面',
    dataIndex: 'cover',
    width: 100,
    align: 'center',
  },
  {
    title: '初始提示词',
    dataIndex: 'initPrompt',
    width: 200,
    ellipsis: true,
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    width: 100,
    align: 'center',
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    width: 80,
    align: 'center',
  },
  {
    title: '部署时间',
    dataIndex: 'deployedTime',
    width: 160,
    align: 'center',
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 数据
const data = ref<API.AppVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listAppVoByPageByAdmin({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 重置
const doReset = () => {
  Object.assign(searchParams, {
    pageNum: 1,
    pageSize: 10,
    appName: '',
    userId: '',
    codeGenType: '',
  })
  fetchData()
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

// 切换精选状态
const toggleFeatured = async (app: API.AppVO) => {
  if (!app.id) return

  const newPriority = app.priority === 99 ? 0 : 99

  try {
    const res = await updateAppByAdmin({
      id: app.id,
      priority: newPriority,
    })

    if (res.data.code === 0) {
      message.success(newPriority === 99 ? '已设为精选' : '已取消精选')
      // 刷新数据
      fetchData()
    } else {
      message.error('操作失败：' + res.data.message)
    }
  } catch (error) {
    console.error('操作失败：', error)
    message.error('操作失败')
  }
}

// 删除应用
const deleteApp = async (id: number | undefined) => {
  if (!id) return

  try {
    const res = await deleteAppByAdmin({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 24px;
}

.search-title {
  margin: 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  font-weight: 600;
}

.search-form {
  margin-top: 16px;
}

.search-form :deep(.ant-form-item-label > label) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.search-form :deep(.ant-input),
.search-form :deep(.ant-select-selector) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: #ffffff;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.search-form :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

.search-form :deep(.ant-input:focus),
.search-form :deep(.ant-select-focused .ant-select-selector) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
  background: rgba(255, 255, 255, 0.15);
}

.search-form :deep(.ant-select-arrow) {
  color: rgba(255, 255, 255, 0.6);
}

/* 搜索框和选择器尺寸优化 */
.search-input {
  width: 200px !important;
}

.search-select {
  width: 180px !important;
}

.search-form :deep(.ant-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}

.app-table {
  margin-top: 24px;
}

.cover-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-image {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.admin-page-content {
  max-width: 85%;
  margin: 0 auto;
}

.no-cover {
  width: 80px;
  height: 60px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px dashed rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  gap: 4px;
}

.prompt-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: rgba(255, 255, 255, 0.8);
}

.type-tag {
  background: rgba(59, 130, 246, 0.2);
  border: 1px solid rgba(59, 130, 246, 0.4);
  color: #93c5fd;
  border-radius: 6px;
}

.featured-tag {
  background: rgba(245, 158, 11, 0.2);
  border: 1px solid rgba(245, 158, 11, 0.4);
  color: #fbbf24;
  border-radius: 6px;
}

.priority-text {
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

.time-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
}

.not-deployed {
  color: rgba(255, 255, 255, 0.5);
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .app-table {
    font-size: 13px;
  }

  .prompt-text {
    max-width: 150px;
  }
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form :deep(.ant-form-item) {
    margin-bottom: 16px;
  }

  .app-table {
    font-size: 12px;
  }

  .cover-image {
    width: 60px;
    height: 45px;
  }

  .no-cover {
    width: 60px;
    height: 45px;
    font-size: 10px;
  }

  .prompt-text {
    max-width: 120px;
  }

  .time-text {
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .app-table {
    font-size: 11px;
  }

  .cover-image {
    width: 50px;
    height: 38px;
  }

  .no-cover {
    width: 50px;
    height: 38px;
    font-size: 9px;
  }
}

/* 自定义滚动条样式 */
:deep(.ant-table-body) {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb:hover) {
  background: rgba(255, 255, 255, 0.5);
}

/* 表格行悬停效果 */
:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(255, 255, 255, 0.05) !important;
}
</style>
